<template>
  <div class="app-container">
    <div class="app-main">
      <div class="mainName">监测点管理</div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="灭治状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="users in extinctionStateList"
              :key="users.value"
              :label="users.label"
              :value="users.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="白蚁防治公司" prop="controlName">
          <el-input
            v-model="queryParams.controlName"
            placeholder="请输入"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="监测公司" prop="monitorName">
          <el-input
            v-model="queryParams.monitorName"
            placeholder="请输入"
            size="small"
          ></el-input>
          <!-- <el-select
            v-model="queryParams.monitorId"
            size="small"
            placeholder="请选择"
            :disabled="detailDis"
            clearable
          >
            <el-option
              v-for="item in jcCompanyList"
              :key="item.monitorId"
              :label="item.monitorName"
              :value="item.monitorId"
            >
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
        <el-form-item style="float: right">
          <!-- <file-upload
            :isShowTip="false"
            :limit="1"
            :fileList="fileList"
            @uploadSuccess="uploadSuccess"
            @uploadError="uploadError"
          >
            <template slot="buttonText">上传</template>
          </file-upload> -->
          <div class="action-group">
            <el-button
              type="primary"
              size="small"
              :loading="refreshLoading"
              @click="refreshDevice()"
              >刷新设备</el-button
            >
            <el-button type="primary" size="mini" @click="download"
              >导出模板</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="downloadData"
              style="margin-left: 0"
              >导出数据</el-button
            >
            <el-upload
              :action="uploadFileUrl"
              :headers="headers"
              :show-file-list="false"
              accept=".xls,.xlsx"
              :before-upload="beforeExcelUpload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <el-button type="primary" size="mini">上传</el-button>
            </el-upload>

            <el-button
              type="danger"
              size="mini"
              @click="handleDelete"
              :disabled="!delShow"
              >删除选中</el-button
            >
          </div>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="assetList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column
          label="序号"
          align="center"
          type="index"
        >
        </el-table-column> -->
        <el-table-column label="点位号" align="center" prop="id" />
        <el-table-column
          label="所属项目"
          align="center"
          prop="projectName"
          width="200"
        />
        <el-table-column
          label="所属白蚁防治公司"
          align="center"
          prop="controlName"
          width="200"
        />
        <el-table-column
          label="小区物业公司"
          min-width="200"
          align="center"
          prop="propertyManagementCompany"
        />
        <el-table-column
          label="小区性质"
          min-width="200"
          align="center"
          prop="projectType"
        />
        <el-table-column
          label="灭治状态"
          align="center"
          prop="status"
          min-width="200"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status === '1'">无蚁</span>
            <span v-else-if="scope.row.status === '2'">有白蚁</span>
            <span v-else-if="scope.row.status === '3'">灭杀中</span>
            <span v-else-if="scope.row.status === '6'">已灭杀</span>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="createTime"
          width="200"
        />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="220"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="editdetail(scope.row)"
              >编辑
            </el-button>
            <el-button size="mini" type="text" @click="seedetail(scope.row)"
              >详情
            </el-button>
            <el-button size="mini" type="text" @click="seeLog(scope.row)"
              >日志
            </el-button>
            <el-button
              size="mini"
              type="text"
              style="color: red"
              @click="deleteItem(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </div>
    <detail
      v-if="detailShow"
      :show="detailShow"
      :myTitle="myTitle"
      :detailDis="detailDisabled"
      :myForm="submitForm"
      :jcCompanyList="jcCompanyList"
      @closeMsg="closeDetail"
    ></detail>
    <log v-if="logShow" :show="logShow" :id="id" @closeMsg="closeLog"></log>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getUserlist } from "@/api/system/user";
import {
  queryMonitorPoint, // 监测点管理数据查询
  insertPointMonitor, // 监测点数据
  updatePointMonitor, // 监测点数据编辑
  delPointMonitorByIds, // 监测点数据删除(单个或批量)
  queryMonitorCompanyData, // 监测公司查询
  queryMonitorPointOne, // 监测点管理数据查询单条数据
  queryHandleLog, // 查询处理
  downloadDeviceDataTemplate,
  downloadDeviceData,
  refreshDevice, // 刷新设备
} from "@/api/manage/asset";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import detail from "./components/detail";
import log from "./components/log";

export default {
  name: "JcPointManage",
  dicts: [],
  components: { detail, log },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/termite/uploadDeviceData",
      headers: {
        "x-access-token": getToken(),
      },
      // 上传限制（单位：MB）
      excelMaxSizeMb: 10,
      logShow: false,
      detailShow: false,
      detailDisabled: false,
      detailDis: false,
      myTitle: "详情",
      delShow: false,
      delItemList: [],
      id: null,
      submitForm: {
        id: "",
        monitorName: "",
        monitorId: "",
        location: "",
        projectName: "",
        controlName: "",
        relay: "",
        rssi: "",
        snr: "",
        voltage: "",
      },
      // 遮罩层
      loading: false,
      // 刷新设备loading
      refreshLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      messageTotal: 0,
      // 资产信息表格数据
      assetList: [],
      messageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 启用日期时间范围
      daterangeStartDate: [],
      options: [
        {
          value: "1",
          label: "公司1",
        },
      ],
      extinctionStateList: [
        {
          value: "初始",
          label: "初始",
        },
        {
          value: "正常",
          label: "正常",
        },
        {
          value: "有蚁",
          label: "有蚁",
        },
        {
          value: "灭杀中",
          label: "灭杀中",
        },
        {
          value: "已灭杀",
          label: "已灭杀",
        },
        {
          value: "离线",
          label: "离线",
        },
        {
          value: "丢失",
          label: "丢失",
        },
      ],
      // 归属账号下拉选项
      statusList: [
        {
          value: "初始",
          label: "初始",
        },
        {
          value: "结束",
          label: "结束",
        },
      ],
      // 打印弹出层
      openPrint: false,
      assets: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "",
        controlName: "",
        monitorName: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 导入结果弹出框
      resultVisible: false,
      // 人员下拉
      personnels: [],
      // 部门下拉
      departments: [],
      jcCompanyList: [],
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    // 刷新设备
    refreshDevice() {
      this.refreshLoading = true;
      refreshDevice()
        .then((res) => {
          if (res.errorCode == "000000") {
            this.$message.success("刷新成功");
            this.getList();
          }
        })
        .catch((error) => {
          console.error("刷新设备失败:", error);
          this.$message.error("刷新失败，请稍后重试");
        })
        .finally(() => {
          this.refreshLoading = false;
        });
    },
    // 上传前校验：仅允许 xls/xlsx，大小限制
    beforeExcelUpload(file) {
      const ext = file.name.split(".").pop().toLowerCase();
      const allow = ["xls", "xlsx"];
      if (!allow.includes(ext)) {
        this.$message.error("仅支持上传 Excel 文件（.xls 或 .xlsx）");
        return false;
      }
      const sizeOk = file.size / 1024 / 1024 <= this.excelMaxSizeMb;
      if (!sizeOk) {
        this.$message.error(`文件大小不能超过 ${this.excelMaxSizeMb} MB`);
        return false;
      }
      this.$modal &&
        this.$modal.loading &&
        this.$modal.loading("正在上传，请稍候...");
      return true;
    },
    // 上传成功
    uploadSuccess(res) {
      this.$modal && this.$modal.closeLoading && this.$modal.closeLoading();
      if (res && (res.errorCode === "000000" || res.code === "000000")) {
        this.$message.success("导入成功");
        this.getList();
      } else {
        const msg =
          (res && (res.msg || res.errorMsg || res.message)) || "导入失败";
        this.$message.error(msg);
      }
    },
    // 上传失败
    uploadError(err) {
      this.$modal && this.$modal.closeLoading && this.$modal.closeLoading();
      this.$message.error("上传失败，请重试");
      console.log(err);
    },
    download() {
      console.log("导出");
      downloadDeviceDataTemplate()
        .then((res) => {
          console.log(res, "导出成功");
          this.$download.saveAs(res, `模板${new Date().getTime()}.xlsx`);
          this.$message.success("导出成功！");
        })
        .catch((err) => {
          console.log(err, "导出失败");
          this.$message.error("导出失败，请重试！");
        });
    },
    downloadData() {
      console.log("导出数据");
      const data = {
        status: this.queryParams.status,
        controlName: this.queryParams.controlName,
        monitorName: this.queryParams.monitorName,
      };
      downloadDeviceData(data).then((res) => {
        console.log(res, "导出成功");
        this.$download.saveAs(res, `监测点数据${new Date().getTime()}.xlsx`);
        this.$message.success("导出成功！");
      });
    },
    closeDetail(val) {
      this.detailShow = false;
      if (val) {
        this.getList();
      }
    },
    closeLog(val) {
      this.logShow = false;
      if (val) {
        this.getList();
      }
    },
    changeItem(val) {
      console.log(val, "0000");
      this.submitForm.monitorName = this.jcCompanyList.find(
        (item) => item.monitorId === val,
      ).monitorName;
    },
    init() {
      queryMonitorCompanyData().then((res) => {
        if (res.errorCode == "000000") {
          this.jcCompanyList = res.data;
        }
      });
    },
    refresh() {
      queryMonitorPointOne(this.id).then((res) => {
        if (res.errorCode === "000000") {
          const { data } = res;
          (this.submitForm.id = data.id),
            (this.submitForm.monitorName = data.monitorName),
            (this.submitForm.location = data.location),
            (this.submitForm.projectName = data.projectName),
            (this.submitForm.projectId = data.projectId),
            (this.submitForm.controlName = data.controlName),
            (this.submitForm.relay = data.relay),
            (this.submitForm.rssi = data.rssi),
            (this.submitForm.snr = data.snr),
            (this.submitForm.voltage = data.voltage);
        }
      });
    },
    handleSelectionChange(val) {
      console.log(val, "00000");
      this.delItemList = val.map((item) => {
        return {
          id: item.id,
        };
      });

      if (val.length > 0) {
        this.delShow = true;
      } else {
        this.delShow = false;
      }
    },
    editdetail(row) {
      console.log(row, "想去");
      this.myTitle = "编辑";
      this.detailDis = false; // 控制是否禁用
      this.id = row.id;
      this.refresh();
      this.detailShow = true;
      this.detailDisabled = false;
    },
    seedetail(row) {
      this.myTitle = "详情";
      this.detailDis = true;
      this.id = row.id;
      this.refresh();
      this.detailShow = true;
      this.detailDisabled = true;
    },
    seeLog(row) {
      console.log(row, "日志");
      this.id = row.id;
      this.logShow = true;
      // queryHandleLog({id: row.pointId}).then(res => {
      //   if(res.errorCode == '000000') {
      //     this.messageList = res.data.records
      //     this.messageTotal = this.messageList.length;
      //   }
      // })
    },
    deleteItem(row) {
      this.$modal.confirm(`是否确认删除点位号位${row.id}的点位？`).then(() => {
        delPointMonitorByIds([row.id]).then((res) => {
          if (res.errorCode == "000000") {
            this.$modal.msgSuccess("删除成功！");
            this.getList();
          }
        });
      });
    },
    /** 查询资产信息列表 */
    getList() {
      this.loading = true;
      queryMonitorPoint(this.queryParams)
        .then((res) => {
          if (res.errorCode == "000000") {
            console.log(res, "sssss");
            this.assetList = res.data.list;
            this.total = res.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = [];
      console.log(this.delItemList);

      this.delItemList.forEach((item) => {
        ids.push(item.id);
      });
      // const ids = row.id || this.ids;
      console.log(ids, "11111111");

      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPointMonitorByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-main {
  background-color: #fff;
  // padding: 15px 20px;
  border-radius: 8px;
  .action-group {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .btnGroupLeft {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 15px 0;
  }
  .formBox {
    .left {
      display: inline-block;
      height: 44px;
      line-height: 44px;
      width: 140px;
      padding-right: 15px;
      border-left: 1px solid #e4e4dc;
      border-right: 1px solid #e4e4dc;
      font-family: MicrosoftYaHei;
      font-size: 12px;
      color: #303133;
      text-align: right;
      vertical-align: top;
    }
    .right {
      display: inline-block;
      width: calc(100% - 140px);
      height: 44px;
      border-right: 1px solid #e4e4dc;
      padding: 6px 15px;
      .el-select {
        width: 340px !important;
      }
      .el-input {
        width: 340px !important;
      }
    }
    .formHead {
      width: 100%;
      height: 44px;
      background-color: #5d6d7f;
      height: 44px;
      line-height: 44px;
      text-align: center;
      font-family: MicrosoftYaHei, MicrosoftYaHei;
      font-weight: bold;
      font-size: 12px;
      color: #ffffff;
    }
    .formWhite {
      width: 100%;
      height: 44px;
      background-color: #fff;
    }
    .formGray {
      width: 100%;
      height: 44px;
      background-color: #dbe2e6;
    }
  }
  .mainName {
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 500;
    font-size: 16px;
    height: 30px;
    line-height: 30px;
    color: #000000;
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }
}
.el-collapse .el-collapse-item__header {
  font-size: 16px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  width: 100%;
}

.pagination-container .el-pagination {
  display: flex;
  justify-content: center;
  width: 100%;
}
</style>
